<template>
    <div class="captcha-container">
        <!-- 验证码显示区域 -->
        <canvas ref="captchaCanvas" width="100" height="40" @click="generateCaptcha"></canvas>
    </div>
</template>

<script>
export default {
    data() {
        return {
            captchaText: '', // 存储生成的验证码
            userInput: '', // 用户输入的验证码
            message: '', // 验证结果提示
            isSuccess: false // 验证是否成功
        };
    },
    mounted() {
        this.generateCaptcha(); // 组件挂载时生成验证码
    },
    methods: {
        // 生成验证码
        generateCaptcha() {
            const canvas = this.$refs.captchaCanvas;
            const ctx = canvas.getContext('2d');

            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // 生成随机验证码
            const chars = '0123456789';
            let captcha = '';
            for (let i = 0; i < 4; i++) {
                captcha += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            this.captchaText = captcha;

            // 绘制验证码
            ctx.font = '30px Arial';
            ctx.fillStyle = this.getRandomColor();
            ctx.fillText(captcha, 10, 35);

            // 添加干扰线
            for (let i = 0; i < 5; i++) {
                ctx.strokeStyle = this.getRandomColor();
                ctx.beginPath();
                ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
                ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
                ctx.stroke();
            }

            // 添加干扰点
            for (let i = 0; i < 50; i++) {
                ctx.fillStyle = this.getRandomColor();
                ctx.beginPath();
                ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, Math.PI * 2);
                ctx.fill();
            }
        },

        // 生成随机颜色
        getRandomColor() {
            const r = Math.floor(Math.random() * 256);
            const g = Math.floor(Math.random() * 256);
            const b = Math.floor(Math.random() * 256);
            return `rgb(${r}, ${g}, ${b})`;
        },

        // 验证用户输入
        validateCaptcha() {
            if (this.userInput === this.captchaText) {
                this.message = '验证码正确！';
                this.isSuccess = true;
            } else {
                this.message = '验证码错误，请重试！';
                this.isSuccess = false;
            }
        }
    }
};
</script>

<style>
.captcha-container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

canvas {
    border: 1px solid #ccc;
}

input {
    margin-bottom: 10px;
    padding: 5px;
    font-size: 16px;
}

button {
    margin: 5px;
    padding: 5px 10px;
    font-size: 16px;
    cursor: pointer;
}

.success {
    color: green;
}

.error {
    color: red;
}
</style>